<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SimpleMarkdownChat - AI智能助手演示</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="marked.min.js"></script>
    <script src="purify.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .chat-container {
            width: 100%;
            height: 100vh;
            background: white;
            border-radius: 20px;
            box-shadow: 0 15px 50px rgba(0, 0, 0, 0.2);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(to right, #4e54c8, #8f94fb);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }

        .chat-header h1 {
            font-size: 1.8rem;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .chat-header p {
            opacity: 0.8;
            font-size: 0.9rem;
        }

        .ai-indicator {
            position: absolute;
            top: 20px;
            right: 20px;
            display: flex;
            align-items: center;
            background: rgba(255, 255, 255, 0.2);
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
        }

        .ai-indicator .status-dot {
            width: 8px;
            height: 8px;
            background-color: #4ade80;
            border-radius: 50%;
            margin-right: 8px;
            animation: pulse 1.5s infinite;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f5f7fb;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .message {
            max-width: 80%;
            padding: 14px 18px 14px 30px;
            border-radius: 18px;
            line-height: 1.5;
            position: relative;
            animation: fadeIn 0.3s ease-out;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .user-message {
            background: #4e54c8;
            color: white;
            align-self: flex-end;
            border-bottom-right-radius: 5px;
        }

        .ai-message {
            background: white;
            color: #333;
            align-self: flex-start;
            border-bottom-left-radius: 5px;
            border: 1px solid #eaeaea;
        }

        .ai-typing {
            align-self: flex-start;
            background: white;
            border-radius: 18px;
            padding: 14px 18px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            border: 1px solid #eaeaea;
        }

        .typing-indicator {
            display: flex;
            align-items: center;
        }

        .typing-indicator span {
            height: 8px;
            width: 8px;
            background: #a777e3;
            border-radius: 50%;
            margin: 0 2px;
            display: inline-block;
        }

        .typing-indicator span:nth-child(1) {
            animation: bounce 1.3s infinite 0.1s;
        }

        .typing-indicator span:nth-child(2) {
            animation: bounce 1.3s infinite 0.2s;
        }

        .typing-indicator span:nth-child(3) {
            animation: bounce 1.3s infinite 0.3s;
        }

        .chat-input-container {
            padding: 15px;
            background: white;
            border-top: 1px solid #eee;
        }

        .input-group {
            display: flex;
            gap: 10px;
        }

        #message-input {
            flex: 1;
            padding: 5px 20px;
            border: none;
            background: #f5f7fb;
            border-radius: 12px;
            font-size: 1rem;
            outline: none;
            transition: all 0.3s;
            resize: none;
            height: 80px;
            line-height: 1.5;
        }

        #message-input:focus {
            background: #e6ebf5;
            box-shadow: 0 0 0 2px rgba(110, 142, 251, 0.3);
        }

        #send-button {
            background: #4e54c8;
            color: white;
            border: none;
            width: 56px;
            height: 80px;
            border-radius: 12px;
            font-size: 1.4rem;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #send-button:hover {
            background: #3d43b7;
            transform: translateY(-2px);
        }

        #send-button:active {
            transform: translateY(0);
        }

        .ai-identity {
            display: flex;
            align-items: center;
            font-size: 0.85rem;
            color: #6c757d;
            margin-bottom: 5px;
        }

        .ai-identity .ai-icon {
            margin-right: 8px;
            color: #8f94fb;
        }

        .system-info {
            text-align: center;
            font-size: 0.85rem;
            color: #a0aec0;
            margin: 10px 0;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes pulse {
            0% {
                opacity: 0.6;
            }
            50% {
                opacity: 1;
            }
            100% {
                opacity: 0.6;
            }
        }

        @keyframes bounce {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-5px);
            }
        }

        @media (max-width: 600px) {
            .chat-container {
                height: 95vh;
                border-radius: 15px;
            }

            .chat-header {
                padding: 15px;
            }

            .message {
                max-width: 90%;
            }

            #send-button {
                width: 50px;
                height: 50px;
            }
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="chat-header">
        <h1>qwen-plus AI智能助手</h1>
        <p>支持Markdown格式的AI智能助手</p>
        <div class="ai-indicator">
            <span class="status-dot"></span>
            AI在线
        </div>
    </div>

    <div class="chat-messages" id="chat-messages">
        <div class="message ai-message">
            <div class="ai-identity">
                <i class="fas fa-robot ai-icon"></i>
                <span>智能助手</span>
            </div>
            <div class="message-content">
                小助手来啦！❤
            </div>
        </div>
    </div>

    <div class="system-info">
        <i class="fas fa-info-circle"></i> 谨慎辨别Ai回答内容！
    </div>

    <div class="chat-input-container">
        <div class="input-group">
            <c:if test="${sessionScope.user!=null}">
                <textarea id="message-input" placeholder="输入您的问题... (支持多行输入，Shift+Enter换行)" autofocus></textarea>
                <button id="send-button">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </c:if>
            <c:if test="${sessionScope.user==null}">
                <textarea id="message-input" placeholder="请先登录！" readonly></textarea>
                <button id="send-button" disabled>
                    <i class="fas fa-paper-plane"></i>
                </button>
            </c:if>
        </div>
    </div>
</div>

<script>
    // DOM元素引用
    const chatMessages = document.getElementById('chat-messages');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    // 添加第一条消息后滚动到底部
    scrollToBottom();
    // 发送按钮点击事件
    sendButton.addEventListener('click', sendMessage);
    // 回车键发送消息（Shift+Enter换行）
    messageInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
    // 发送消息函数
    async function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;
        // 添加用户消息
        addUserMsg(message)
        //开始获取AI回复
        await chatAI(message)
    }
    function addUserMsg(message){
        const messageDiv = document.createElement('div');
        messageDiv.className = `message user-message`;
        messageDiv.innerHTML = `<div class="message-content">`+DOMPurify.sanitize(message)+`</div>`;
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
        // 清空输入框
        messageInput.value = '';
    }

    //开始获取AI回复
    async function chatAI(message){
        showTypingIndicator();//显示AI正在输入
        let currentReader;
        try {
            // 使用 Fetch 发送请求
            const response = await fetch(`/chat?message=` + encodeURIComponent(message));
            if (!response.ok) throw new Error('Network error');
            // 获取流式读取器
            currentReader = response.body.getReader();
            const decoder = new TextDecoder();
            let aiResponse = '';
            let contentDiv = addAiMsg();//ai返回的消息内容容器
            removeTypingIndicator();//移除AI正在输入
            // 读取流式数据
            while (true) {
                const { done, value } = await currentReader.read();
                if (done) break;
                const chunk = decoder.decode(value, { stream: true });// 解码数据块
                console.log(chunk)
                aiResponse += chunk;
                contentDiv.innerHTML = DOMPurify.sanitize(marked.parse(aiResponse))
                scrollToBottom();
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            currentReader = null;
        }
    }
    /**
     * 添加AI消息到聊天窗口
     */
    function addAiMsg() {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ai-message`;
        messageDiv.innerHTML = `
                <div class="ai-identity">
                    <i class="fas fa-robot ai-icon"></i>
                    <span>智能助手</span>
                </div>
            `;
        const contentDiv = document.createElement('div');
        contentDiv.className = "message-content"
        messageDiv.appendChild(contentDiv)
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
        return contentDiv;
    }
    // 显示AI正在输入
    function showTypingIndicator() {
        const typingDiv = document.createElement('div');
        typingDiv.className = 'ai-typing';
        typingDiv.id = 'typing-indicator';
        typingDiv.innerHTML = `
                <div class="ai-identity">
                    <i class="fas fa-robot ai-icon"></i>
                    <span>正在输入...</span>
                </div>
                <div class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            `;

        chatMessages.appendChild(typingDiv);
        scrollToBottom();
    }
    // 移除输入指示器
    function removeTypingIndicator() {
        const indicator = document.getElementById('typing-indicator');
        if (indicator) {
            indicator.remove();
        }
    }
    // 滚动到底部
    function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    //初始化，请求历史消息，如果没有则发起打招呼
    async function fetchChatMessages() {
        try {
            const response = await fetch('/messages');
            if (!response.ok) {
                throw new Error(`HTTP error! status: `+response.status);
            }
            const respData = await response.json();
            let messages = respData.data
            if(messages.length === 0){
                //初始化 自动添加欢迎信息
                let contentDiv = addAiMsg();
                contentDiv.innerHTML = "你好，我是AI小助手呀，请随时提问！"
                //await chatAI("你好");//自动触发打招呼
                return
            }
            // 打印所有消息
            console.log("=== All Messages ===");
            console.log(messages);
            messages.forEach(msg => {
                if(msg.type === 'user'){
                    addUserMsg(msg.msg)
                }else if(msg.type === 'assistant'){
                    let contentDiv = addAiMsg();
                    contentDiv.innerHTML = DOMPurify.sanitize(marked.parse(msg.msg))
                }
            });
        } catch (error) {
            console.error("Error fetching messages:", error);
        }
    }
    // 调用函数执行请求
    fetchChatMessages();
</script>
</body>
</html>
